package ducpham.rogueconsole.mark1;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.util.HashMap;

public class CharacterSpriteCanvas {

	private int width;
	private int height;
	private Font font;
	private FontRenderContext frc = new FontRenderContext(null, true, true);

	private HashMap<Character, Image> canvas = new HashMap<Character, Image>();

	public CharacterSpriteCanvas(Font font) {
		this.font = font;
		Image img = new BufferedImage(1, 1, BufferedImage.TRANSLUCENT);
		Graphics2D g = (Graphics2D) img.getGraphics();

		width = (int) g.getFontMetrics(font).getMaxCharBounds(g).getWidth() + 1;
		height = (int) g.getFontMetrics(font).getMaxCharBounds(g).getHeight() + 1;
	}

	public Image getCharImage(char c) {

		if (canvas.containsKey(new Character(c)))
			return canvas.get(c);

		Image img = new BufferedImage(width, height * 2, BufferedImage.TRANSLUCENT);
		Graphics2D g = (Graphics2D) img.getGraphics();

		TextLayout tl = new TextLayout(String.valueOf(c), font, frc);
		int realTextWidth = (int) tl.getBounds().getWidth();
		tl.draw(g, (width - realTextWidth) / 2, height * 3/4 + 1);

		canvas.put(c, img);
		return img;
	}

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}
}
